<template>
  <el-dialog :title="fileName" :model-value='props.visible' width="80%" top="5vh" @close="btnClose">
    <div class="preview-container">
      <!-- PDF预览 -->
      <!-- <div class="pdf-container" v-if="fileType === 'pdf'" ref="pdfContainer"></div> -->
      <vue-office-pdf
        v-if="fileType === 'pdf'"
        :src="previewPdfUrl"
        style="height: 80vh"
    />
      <!-- 图片预览 -->
      <el-image 
        v-else-if="isImage" 
        :src="previewUrl" 
        :preview-src-list="[previewUrl]" 
        fit="contain"
        style="max-height: 70vh;"
      />
      <video
        v-else-if="isvideo"
        :src="previewPdfUrl"
        controls
        autoplay
        class="play-video"
      ></video>
      <!-- <video   v-else-if="isvideo" controls 
      autoplay :src="previewPdfUrl"   > 
        <source :src="`${staticURL}${item.url}`" type="video/mp4">
      </video> -->
      <!-- 文本预览 -->
      <pre v-else-if="fileType === 'txt'">{{ fileContent }}</pre>
      
      <!-- Markdown预览 -->
      <div v-else-if="fileType === 'md'" v-html="renderedMarkdown" class="markdown-view" ></div>
      
      <!-- Excel预览 -->
      <!-- <div v-else-if="isExcel" class="excel-container" v-html="excelHtml"></div> -->
      <vue-office-excel
      :options="{xls:true}"
        v-else-if="isExcel"
        :src="previewPdfUrl"
        style="height: 80vh"
    />
      
      <!-- PowerPoint预览 -->
      <!-- <vue-office-pptx
        v-else-if="fileType === 'pptx'"
        :src="previewPdfUrl"
        style="height: 80vh"
        @rendered="handleRendered"
        @error="handleError"
        /> -->
        
      <!-- Word预览 -->
      <div v-else-if="isWord" ref="wordContainer"></div>
      
      <!-- 其他文件 -->
      <div v-else>
        <p>不支持预览此文件类型</p>
        <el-button type="primary" @click="downloadFile(props.fileUrl,props.fileName)">下载文件</el-button>
      </div>
    </div>
    
    <template #footer>
      <el-button @click="btnClose">关闭</el-button>
      <!-- <el-button type="primary" @click="downloadFile">下载</el-button> -->
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// import { ref, computed, watch, onMounted } from 'vue';
import { renderAsync } from 'docx-preview';
// import * as XLSX from 'xlsx';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import VueOfficePdf from '@vue-office/pdf/lib/v3/vue-office-pdf.mjs'
import VueOfficeExcel from '@vue-office/excel'
// import VueOfficePptx from '@vue-office/pptx/lib/v3/vue-office-pptx.mjs'
//引入相关样式
import '@vue-office/excel/lib/index.css'

const props = withDefaults(defineProps<{
  fileUrl?: string;
  fileName?: string;
  visible: boolean;
}>(), {
  fileUrl: '',
  fileName: '',
  visible: false
})
const emit = defineEmits(['update']);

// 计算文件类型
const fileType = computed(() => {
  const ext = props.fileName?.split('.').pop().toLowerCase();
  return ext || '';
});

// 判断文件类型
const isImage = computed(() => ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(fileType.value));
const isExcel = computed(() => ['xlsx', 'xls', 'csv'].includes(fileType.value));
const isWord = computed(() => ['docx'].includes(fileType.value));
const isvideo = computed(() => ['mp4', 'webm', 'mov'].includes(fileType.value));
const btnClose = () => {
  emit('update');
}

// const pdfContainer = ref(null);
const wordContainer = ref<any>(null);
const fileContent = ref('');
const renderedMarkdown = ref('');
// const excelHtml = ref('');
const previewUrl = ref('');
const previewPdfUrl = ref('');

// 主要预览方法
const previewFile = async () => {
  if (!props.fileUrl) return;
  
  try {
    const response = await fetch(props.fileUrl);
    const blob = await response.blob();
    previewPdfUrl.value = props.fileUrl; // 用于PDF预览
    // 图片直接使用URL
    if (isImage.value) {
      previewUrl.value = URL.createObjectURL(blob);
      return;
    }
    
    // 其他文件类型处理
    switch (fileType.value) {
      // case 'pdf':
      //   await renderPdf(blob);
      //   break;
      case 'txt':
        fileContent.value = await blob.text();
        break;
      case 'md':
        const text = await blob.text();
        // renderedMarkdown.value = new MarkdownIt().render(text);
         renderMd(text)
        break;
      // case 'xlsx':
      // case 'xls':
      //   await renderExcel(blob);
      //   break;
      case 'docx':
        await renderDocx(blob);
        break;
      case 'doc':
        await renderDocx(blob);
        break;
    }
  } catch (error) {
    console.error('预览失败:', error);
  }
};
const md = new MarkdownIt({
  html: true,        // 允许HTML标签
  linkify: true,
  highlight: (code, lang) => {  // 代码高亮
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value;
    }
    return code;
  }
});
// 渲染md文件
function renderMd(content:string){

renderedMarkdown.value= md.render(content)
const dom=document.querySelector('.markdown-view') as any;
  //  dom.className = '.markdown-img';
  
}
// DOCX渲染
const renderDocx = async (blob) => {
  const arrayBuffer = await blob.arrayBuffer();
  await renderAsync(arrayBuffer, wordContainer.value);
};

// DOC渲染 (使用mammoth转换为HTML)
// const renderDoc = async (blob) => {
//   const arrayBuffer = await blob.arrayBuffer();
//   console.log('DOC文件转换为ArrayBuffer', arrayBuffer,mammoth);
//   const result = await mammoth.convertToHtml({ arrayBuffer });
//  console.log('DOC文件转换结果', result);
//   wordContainer.value.innerHTML = result.value;
// };
// 下载
async function downloadFile(url, filename) {
  const response = await fetch(url);
  const blob = await response.blob();
  const blobUrl = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = blobUrl;
  a.download = filename; // 现在会使用你指定的文件名
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  
  // 释放内存
  setTimeout(() => URL.revokeObjectURL(blobUrl), 100);
}

// 监听可见性变化
// watch(() => props.visible, (val) => {
//   if (val) previewFile();
// });
onMounted(() => {
  
  if (props.visible) {
    previewFile();
  }
  
});
</script>

<style scoped lang="scss">
.preview-container {
  min-height: 60vh;
  max-height: 80vh;
  overflow: auto;
}
.pdf-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.excel-container {
  overflow: auto;
}
 .markdown-view{
  // height: 0 !important;
  line-height: 1.6;
  max-width: 80vw;
  height: 80vh;
  word-break: break-word; 
  
}
.markdown-img img{
    width: 100%;
    height: auto;
  
}
.play-video{
  width: 100%;
  height: 80vh;
  object-fit: contain;
}

/* 添加PDF页间距 */
// canvas {
//   display: block;
//   margin-bottom: 10px;
//   border: 1px solid #eee;
// }
</style>
